package org.mvc.persistence;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.mvc.Main;

import java.io.File;
import java.sql.*;

public class Hibernate {

    private static SessionFactory sessionFactory;

    public static String hibernateCfgFile = Main.root_path.concat("main/webapp/WEB-INF/resources/hibernate.cfg.xml");

    private static SessionFactory buildSessionFactory() throws Throwable {
        DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
        
        System.out.println(hibernateCfgFile);
        
        File cfgFile = new File(hibernateCfgFile);

        return new Configuration().configure(cfgFile)
        		.addFile(new File(cfgFile.getParent(), "maps/System.map.xml"))
        		.addFile(new File(cfgFile.getParent(), "maps/Galaxy.map.xml"))
        		.addFile(new File(cfgFile.getParent(), "maps/User.map.xml"))
                .buildSessionFactory()
                ;
    }

    public static SessionFactory getSessionFactory() throws Throwable {
        if (null == sessionFactory) {
            sessionFactory = buildSessionFactory();
        }

        return sessionFactory;
    }

}
